package com.gxgeek.product.service.impl;

import com.gxgeek.product.common.DecreaseStockInput;
import com.gxgeek.product.common.ProductInfoOutput;
import com.gxgeek.product.dataobject.ProductInfo;
import com.gxgeek.product.dto.CartDTO;
import com.gxgeek.product.enums.ProductStatusEnum;
import com.gxgeek.product.enums.ResultEnum;
import com.gxgeek.product.exception.ProductException;
import com.gxgeek.product.exception.SellException;
import com.gxgeek.product.repository.ProductInfoRepository;
import com.gxgeek.product.service.ProductService;
import com.gxgeek.product.service.RedisLock;
import com.gxgeek.product.util.JsonUtil;
import com.rabbitmq.tools.json.JSONUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * Created by Administrator on 2017/7/11.
 */
@Service
//@CacheConfig(cacheNames = "product") 缓存全局配置
public class ProductServiceImpl implements ProductService {
    private static final int TIMEOUT = 10 * 1000; //超时时间 10s

    @Autowired
    private ProductInfoRepository productInfoRepository;
    @Autowired
    private RedisLock redisLock;
    @Autowired
    private AmqpTemplate amqpTemplate;


    @Override
//    @Cacheable(key = "#status") stel 表达式
    public List<ProductInfo> findByProductStatus(Integer status) {
        return productInfoRepository.findByProductStatus(status);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.NEW.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return productInfoRepository.findAll(pageable);
    }

    @Override
    public ProductInfo findOne(String productId) {
        return productInfoRepository.getOne(productId);
    }

    @Override
    @Transactional
//    @CachePut(key = "123")
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoRepository.save(productInfo);
    }

    @Override
    @Transactional
    public void increaseStock(List<CartDTO> list) {
        for (CartDTO cartDTO :list){
            ProductInfo productInfo = productInfoRepository.getOne(cartDTO.getProductID());
            if (productInfo==null){
                throw  new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer result = productInfo.getProductStock()+cartDTO.getProductQuantity();
            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
        }

    }

    @Override
    @Transactional
    public void decreaseSock(List<CartDTO> list) {
        for (CartDTO cartDTO :list){
            ProductInfo productInfo = productInfoRepository.getOne(cartDTO.getProductID());
            if (productInfo==null){
                throw  new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //加锁redis 处理
            long time = System.currentTimeMillis() + TIMEOUT;
            if(!redisLock.lock(productInfo.getProductId(), String.valueOf(time))) {
                throw new SellException(101, "哎呦喂, 人也太多了, 换个姿势再试试~~");
            }
            //减库存
            Integer result = productInfo.getProductStock()-cartDTO.getProductQuantity();
            if (result < 0 ){
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
            //解锁
            redisLock.unlock(productInfo.getProductId(), String.valueOf(time));

        }
    }

    @Override
    public ProductInfo onSale(String productId) {
        ProductInfo productInfo = productInfoRepository.getOne(productId);
        if (productInfo == null){
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        if (productInfo.getProductStatus().intValue() == ProductStatusEnum.NEW.getCode()){
            throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
        }
        productInfo.setProductStatus(ProductStatusEnum.NEW.getCode());
        productInfoRepository.save(productInfo);
        return productInfo;
    }

    @Override
    public ProductInfo offSale(String productId) {
        ProductInfo productInfo = productInfoRepository.getOne(productId);
        if (productInfo == null){
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        if (productInfo.getProductStatus().intValue() == ProductStatusEnum.FINISHED.getCode()){
            throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
        }
        productInfo.setProductStatus(ProductStatusEnum.FINISHED.getCode());
        productInfoRepository.save(productInfo);
        return productInfo;
    }

    @Override
    public List<ProductInfoOutput> findList(List<String> productIdList) {
        List<ProductInfo> productInfoList =  productInfoRepository.findByProductIdIn(productIdList);
        List<ProductInfoOutput> productInfoOutputList = productInfoList.stream().map(
                s -> {
                    ProductInfoOutput productInfoOutput = new ProductInfoOutput();
                    BeanUtils.copyProperties(s, productInfoOutput);
                    return productInfoOutput;
                }
        ).collect(toList());
        return productInfoOutputList;
    }

    @Override
    public List<ProductInfo> decreaseStock(List<DecreaseStockInput> decreaseStockInputList) {
        List<ProductInfo> productInfoList = decreaseStockProcess(decreaseStockInputList);
        List<ProductInfoOutput> productInfoOutputList = productInfoList.stream().map(s -> {
            ProductInfoOutput infoOutput = new ProductInfoOutput();
            BeanUtils.copyProperties(s, infoOutput);
            return infoOutput;
        }).collect(toList());

        amqpTemplate.convertAndSend("productInfo", JsonUtil.toJson(productInfoOutputList));
        return productInfoList;


    }

    @javax.transaction.Transactional
    public List<ProductInfo> decreaseStockProcess(List<DecreaseStockInput> decreaseStockInputList) {
        List<ProductInfo> productInfoList = new ArrayList<>();
        for (DecreaseStockInput decreaseStockInput: decreaseStockInputList) {
            Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(decreaseStockInput.getProductId());
            //判断商品是否存在
            if (!productInfoOptional.isPresent()){
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            ProductInfo productInfo = productInfoOptional.get();
            //库存是否足够
            Integer result = productInfo.getProductStock() - decreaseStockInput.getProductQuantity();
            if (result < 0) {
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
            productInfoList.add(productInfo);
        }
        return productInfoList;
    }


}
